package com.bw.ppjokeplay.mvvm.view

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.graphics.Color
import android.os.Bundle
import android.os.IBinder
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.bw.ppjokeplay.R
import com.bw.ppjokeplay.adapter.MessageAdapter
import com.example.livehome.MsgEntity
import com.example.livehome.TextEntity
import com.example.livehome.TopEntity
import com.example.livehome.webrtc.OnlineUser
import com.example.livehome.webrtc.WebRtcClient
import com.example.livehome.webrtc.jsonToList
import com.google.gson.Gson
import com.opensource.svgaplayer.SVGACallback
import com.opensource.svgaplayer.SVGAImageView
import com.opensource.svgaplayer.SVGAParser
import com.opensource.svgaplayer.SVGAVideoEntity
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import master.flame.danmaku.controller.DrawHandler
import master.flame.danmaku.danmaku.model.BaseDanmaku
import master.flame.danmaku.danmaku.model.DanmakuTimer
import master.flame.danmaku.danmaku.model.IDanmakus
import master.flame.danmaku.danmaku.model.android.DanmakuContext
import master.flame.danmaku.danmaku.model.android.Danmakus
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser
import master.flame.danmaku.ui.widget.DanmakuView
import okhttp3.*
import org.json.JSONArray
import org.json.JSONObject
import org.webrtc.EglBase
import org.webrtc.MediaStream
import tv.danmaku.ijk.media.player.IjkMediaPlayer
import java.io.IOException
import java.util.*
import java.util.concurrent.LinkedBlockingQueue
import kotlin.collections.ArrayList

class LiveHomeActivity : AppCompatActivity(), View.OnClickListener,MsgCallBack {

    private lateinit var live_home_video: StandardGSYVideoPlayer
    private lateinit var live_home_rv : RecyclerView
    private lateinit var live_home_edt : EditText
    private lateinit var live_home_txt: Button
    private lateinit var live_home_top: Button
    private lateinit var live_home_gift: Button
    private lateinit var live_home_phone: Button
    private lateinit var DV:DanmakuView
    private lateinit var live_home_svga : SVGAImageView
    private var connection:MsgConnection = MsgConnection()
    private lateinit var msgService : WebSocketService
    private var svgaListener = SVGAListerner()
    private var svgaList = ArrayList<String>()
    private var giftQueue = LinkedBlockingQueue<String>()
    private var webRtcClient: WebRtcClient? = null
    private val hostUrl = "http://10.161.54.46:3000/"
    private val eglBase by lazy { EglBase.create() }
    private var create: DanmakuContext?=null
    private val E="Lsh"
    var messageAdapter: MessageAdapter = MessageAdapter()
    //初始化svga数据
    private fun initSVGA(){
        svgaList.add("a.svga")
        svgaList.add("b.svga")
        svgaList.add("c.svga")
        svgaList.add("d.svga")
        svgaList.add("e.svga")
        svgaList.add("f.svga")
        svgaList.add("g.svga")
        svgaList.add("h.svga")
        svgaList.add("i.svga")
        svgaList.add("j.svga")
        svgaList.add("k.svga")
        svgaList.add("l.svga")
        svgaList.add("m.svga")
        svgaList.add("n.svga")
        svgaList.add("o.svga")
        svgaList.add("p.svga")
        svgaList.add("q.svga")
        svgaList.add("r.svga")
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        SVGAParser.shareParser().init(this)
        setContentView(R.layout.activity_live_home)
        IjkMediaPlayer.loadLibrariesOnce(null)
        IjkMediaPlayer.native_profileBegin("libijkplayer.so")
        initSVGA()
        initView()
        createLive()
        startWebRTC()
        //绑定获取im消息服务
        var intent  = Intent(this, WebSocketService::class.java)
        bindService(intent, connection, Context.BIND_AUTO_CREATE)
        live_home_rv.layoutManager = LinearLayoutManager(this)
        messageAdapter = MessageAdapter()
        live_home_rv.adapter = messageAdapter

        create = DanmakuContext.create()
        DV.prepare(object : BaseDanmakuParser(){
            override fun parse(): IDanmakus? {
                return Danmakus()
            }
        },create)

        DV.setCallback(object : DrawHandler.Callback {
            override fun prepared() {
                 DV.start()
            }

            override fun updateTimer(timer: DanmakuTimer?) {

            }

            override fun danmakuShown(danmaku: BaseDanmaku?) {

            }

            override fun drawingFinished() {

            }

        })

    }

    private fun initView(){
        live_home_video = findViewById(R.id.live_home_video)
        live_home_rv = findViewById(R.id.live_home_rv)
        live_home_edt = findViewById(R.id.live_home_edt)
        live_home_txt = findViewById(R.id.live_home_txt)
        live_home_top = findViewById(R.id.live_home_top)
        live_home_gift = findViewById(R.id.live_home_gift)
        live_home_svga = findViewById(R.id.live_home_svga)
        live_home_phone = findViewById(R.id.live_home_phone)
        DV = findViewById(R.id.DV)
        live_home_phone.setOnClickListener(this)
        live_home_txt.setOnClickListener(this)
        live_home_top.setOnClickListener(this)
        live_home_gift.setOnClickListener(this)
        live_home_svga.clearsAfterStop = true
        live_home_svga.callback = svgaListener
    }
    //播放拉流视频
    private fun createLive(){
        //设置播放
        live_home_video.setUp(LiveConst.LIVE_URL,false,"sp")
        live_home_video.startPlayLogic()

    }

    override fun onStop() {
        super.onStop()

        unbindService(connection)
    }

    private fun loadAnimation(str : String) {
        val svgaParser : SVGAParser = SVGAParser.shareParser()
        val name = str
        svgaParser.decodeFromAssets(name, object : SVGAParser.ParseCompletion {
            override fun onComplete(videoItem: SVGAVideoEntity) {
                live_home_svga.setVideoItem(videoItem)
                live_home_svga.startAnimation()
//                live_home_svga.stepToFrame(0,true)
            }

            override fun onError() {
                Log.e(E,"SVGA->onError()")
            }

        })
    }

    override fun onClick(v: View?) {
        //根据点击不同按钮成成不同type
        var entity : MsgEntity?= null
        if (R.id.live_home_top == v!!.id){
            entity = TopEntity()
            entity.msgType = 2
            entity.msg = live_home_edt.text.toString()
            entity.colorId = Color.BLUE

            val danmaku: BaseDanmaku = create!!.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL)
            danmaku.text = live_home_edt.text.toString()
            danmaku.padding = 5
            danmaku.priority = 0
            danmaku.isLive = false
            danmaku.time = DV.currentTime + 1200
            danmaku.textSize = 40f
            danmaku.textColor = Color.RED
            DV.addDanmaku(danmaku)

        }else if(R.id.live_home_gift == v!!.id){
            entity = GiftEntity()
            entity.msgType = 3
            entity.giftId = Random().nextInt(svgaList.size-1)
        }else if (R.id.live_home_phone == v!!.id){
            Log.e(E,"开启连麦"+userid)
            webRtcClient?.callByClientId(userid!!)
            return
        } else{
            entity = TextEntity()
            entity.msgType = 1
            entity.msg = live_home_edt.text.toString()
            entity.name = "zzy"
        }
        var jsonStr : String = Gson().toJson(entity).toString()
        var type : MediaType = MediaType.parse("application/json")!!
        var requst: Request = Request.Builder()
            .url(LiveConst.SENDMSGURL).post(
                RequestBody.create(
                    type, jsonStr
                )
            )
            .build()
        OkHttpClient.Builder().build().newCall(requst)
            .enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    Log.e(E, "发消息出错:" + e.message)
                }

                override fun onResponse(call: Call, response: Response) {
                    Log.e(E, "发消息成功:" + response.body()!!.string())
                }

            })
    }

    inner class MsgConnection : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            var binder : WebSocketService.WebSocketBinder = service as WebSocketService.WebSocketBinder
            msgService = binder.getWebSocketService()
            msgService.setMsgCall(this@LiveHomeActivity)
        }

        override fun onServiceDisconnected(name: ComponentName?) {
        }

    }

    override fun msgCall(str: String) {
        //
        if (str .equals("连接成功") ){
            return
        }
        Log.e(E,"msgCall"+str)
        var jsonObject = JSONObject(str)
        var msgEntity : MsgEntity ?=null
        when(jsonObject.getInt("msgType")){
            1 -> {
                msgEntity = Gson().fromJson<TextEntity>(str, TextEntity::class.java)
                var ts=msgEntity as TextEntity
                ToastUtils.showShort(str)
                messageAdapter.data.add(ts.msg!!)
                var a=  messageAdapter.data.size
                messageAdapter.notifyItemInserted(a)

            }
            2 -> {
                msgEntity = Gson().fromJson<TopEntity>(str, TopEntity::class.java)
            }
            3 -> {
                msgEntity = Gson().fromJson<GiftEntity>(str, GiftEntity::class.java)
            }
        }
        Log.e(E,"msgCall"+(msgEntity == null))
        runOnUiThread(object : Runnable {
            override fun run() {
                if (msgEntity!!.msgType == 3){
                    var giftEntity:GiftEntity = msgEntity as GiftEntity
                    giftQueue.put(svgaList.get(giftEntity.giftId))
                    if (!TextUtils.isEmpty(svgaList.get(giftEntity.giftId))&&svgaFlag) {
                        var svgaPath = giftQueue.poll()
                        loadAnimation(svgaPath)
                    }
                }
            }
        })
    }

    var svgaFlag = true
    inner class SVGAListerner : SVGACallback {

        override fun onFinished() {
            svgaFlag = true
            var str  =giftQueue.poll()
            if (!TextUtils.isEmpty(str))
                loadAnimation(str)
        }

        override fun onPause() {
        }

        override fun onRepeat() {
        }

        override fun onStep(frame: Int, percentage: Double) {
            svgaFlag = false
        }

    }

    var userid : String ?="a"

    private fun startWebRTC() {

        webRtcClient = WebRtcClient(
            hostUrl,
            this.application,
            eglBase.eglBaseContext,
            object : WebRtcClient.RtcListener {
                override fun onOnlineIdsChanged(jsonArray: JSONArray) {
                    val list = jsonArray.toString().jsonToList<OnlineUser>() ?: listOf()
                    var i = 0
                    while (i<list.size){
                        if (!list.get(i).id.equals("0")){
                            userid = list.get(i).id
                        }
                        i++
                    }
                }

                override fun onCallReady(callId: String) {
                    runOnUiThread {
                        Toast.makeText(this@LiveHomeActivity, "已连上服务器", Toast.LENGTH_SHORT).show()
                    }
                    webRtcClient?.speak()
                    webRtcClient?.startLocalAudioCapture(android.os.Build.MODEL)
                }

                override fun onStatusChanged(newStatus: String) {
                    runOnUiThread {
                        Toast.makeText(this@LiveHomeActivity, newStatus, Toast.LENGTH_SHORT).show()
                    }
                }

                override fun onLocalStream(localStream: MediaStream) {
                }

                override fun onAddRemoteStream(remoteStream: MediaStream, endPoint: Int) {
                }

                override fun onRemoveRemoteStream(endPoint: Int) {
                }
            })

    }

    override fun onPause() {
        super.onPause()
        webRtcClient?.onPause()
    }

    override fun onResume() {
        super.onResume()
        webRtcClient?.onResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        webRtcClient?.onDestroy()
    }
}